package com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_implement

import android.util.Log
import com.facebook.ads.*
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.BuildConfig
import com.horoscope.astrology.zodiac.signs.free.MmoApplication
import com.horoscope.astrology.zodiac.signs.free.bean.ConfigResultBean
import com.horoscope.astrology.zodiac.signs.free.utils.EventType
import com.horoscope.astrology.zodiac.signs.free.utils.FlurryEventUtil
import com.horoscope.astrology.zodiac.signs.free.utils.interfaceUtils.FaceBookInterstitialListener
import com.horoscope.astrology.zodiac.signs.free.utils.interfaceUtils.FacebookNativeListener
import java.util.*

class LoadFacebookAd private constructor() {

    private val mContext = MmoApplication.getInstance()

    private var interstitialAd: InterstitialAd? = null
    private var mFaceBookInterstitialListener: FaceBookInterstitialListener? = null

    private var iPlacement = ""
    private var nPlacement = ""

    private var nativeAd: NativeAd? = null
    private var mFacebookNativeListener: FacebookNativeListener? = null

    private var adList = Collections.synchronizedList(ArrayList<NativeAd>())
    private var iList = Collections.synchronizedList(ArrayList<InterstitialAd>())

    companion object {
        private val TAG = LoadFacebookAd::class.java.simpleName
        val mInstance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            LoadFacebookAd()
        }
    }

    fun setFaceBookInterstitialListener(listener: FaceBookInterstitialListener) {
        mFaceBookInterstitialListener = listener
    }

    fun setFacebookNativeListener(listener: FacebookNativeListener) {
        mFacebookNativeListener = listener
    }

    /**interstitial广告数据准备，初始化对象，加载对象，显示广告**/
    @Synchronized
    fun initAndLoadInterstitial(bean: ConfigResultBean.AdInfo) {
        if (interstitialAd != null) interstitialAd = null
        interstitialAd = InterstitialAd(mContext, getTestId(bean.id))
        //对于自动播放视频广告，建议加载广告
        //至少提前30秒
        interstitialAd!!.loadAd(
            interstitialAd!!.buildLoadAdConfig().withAdListener(object : InterstitialAdListener {
                override fun onInterstitialDisplayed(ad: Ad) {
                    if (iPlacement != "Supplement") {
                        FlurryEventUtil.putDataToEvent(
                            EventType.TYPE_AD_DISPLAY, "type", iPlacement
                        )
                    }
                }

                override fun onInterstitialDismissed(ad: Ad) {
                    close?.onClose()
                }

                override fun onError(ad: Ad, adError: AdError) {
                    mFaceBookInterstitialListener?.onFacebookFailed(adError.errorMessage!!)
                    Log.e("wsTest", "FB插页Error:${adError.errorMessage}")
                }

                override fun onAdLoaded(ad: Ad) {
                    if (interstitialAd != null && interstitialAd!!.isAdLoaded) {
                        iList.add(interstitialAd)
                        mFaceBookInterstitialListener?.onFacebookAdLoad(bean)
                        Log.e("wsTest", "FB插页成功")
                    }
                }

                override fun onAdClicked(ad: Ad) {
                    FlurryEventUtil.putDataToEvent(EventType.TYPE_AD_CLICK, "type", iPlacement)
                }

                override fun onLoggingImpression(ad: Ad) {}
            })
                .withCacheFlags(CacheFlag.ALL)
                .build()
        )

    }

    fun showInterstitialAd(placement: String, time: Int): Boolean {
        iPlacement = placement //广告显示的位置
        var showFlag = false
        if (iList.isNotEmpty()) {
            iList.firstOrNull()?.let {
                if (it.isAdLoaded) {
                    it.show()
                    iList.remove(it)
//                    GlobalScope.launch(Dispatchers.Main) {
//                        delay(2500L)
//                        ADInterstitialManager.mInstance.getInterstitialFirst()
//                    }
                    supplement()
                    FlurryEventUtil.putDataToEvent(EventType.TYPE_IS_READY, "Interstitial", "True_$time")
                    showFlag = true
                }else{
                    FlurryEventUtil.putDataToEvent(EventType.TYPE_IS_READY, "Interstitial", "False_$time")
                }
            }
        } else {
            AppSettingManager.saveInt(1, "supplement")//没有加载，需要补充一次
        }
        return showFlag
    }

    // 记录广告是否正常显示，是否需要补充，可以提到base通用
    private fun supplement() {
        val supplement = AppSettingManager.readInt("supplement", 0)
        if (supplement == 1) {//补充展示AD，标志位置0
            AppSettingManager.saveInt(0, "supplement")
            FlurryEventUtil.putDataToEvent(
                EventType.TYPE_AD_INTERSTITIAL_DISPLAY, "type", "Supplement"
            )
        } else {//正常展示广告
            FlurryEventUtil.putDataToEvent(
                EventType.TYPE_AD_INTERSTITIAL_DISPLAY, "type", "Correct"
            )
        }
    }

    /**interstitial广告数据准备，初始化对象，加载对象，显示广告**/


    /**Native广告数据准备，初始化对象，加载对象，显示广告**/
    fun loadNativeAd(bean: ConfigResultBean.AdInfo) {
        nativeAd = NativeAd(mContext, getTestId(bean.id))
        nativeAd!!.loadAd(
            nativeAd!!.buildLoadAdConfig().withAdListener(object : NativeAdListener {
                override fun onAdClicked(p0: Ad?) {
                    FlurryEventUtil.putDataToEvent(
                        EventType.TYPE_AD_CLICK, "type", "Native Content"
                    )
                }

                override fun onMediaDownloaded(p0: Ad?) {
                    if (nativeAd === p0) {
                        mFacebookNativeListener?.onFacebookNativeLoad(bean, nativeAd!!)
                        adList.add(nativeAd!!)
                        Log.e("wsTest", "FBNative成功")
                    }
                }

                override fun onError(p0: Ad?, adError: AdError) {
                    mFacebookNativeListener?.onFacebookNativeFailed(adError.errorMessage)
                    Log.e("wsTest", "FBNative 加载失败" + adError.errorMessage)
                }

                override fun onAdLoaded(ad: Ad?) {
                    if (nativeAd == null || nativeAd !== ad) {
                        mFacebookNativeListener?.onFacebookNativeFailed("null || !=ad")
                        return
                    }
                }

                override fun onLoggingImpression(p0: Ad?) {
                }
            }).withMediaCacheFlag(NativeAdBase.MediaCacheFlag.ALL).build()
        )
    }

    fun getFacebookNativeAd(placement: String, time:Int): NativeAd? {
        nPlacement = placement
        var temp: NativeAd? = null  // 展示所需对象
        if (adList.isNotEmpty()) {
            temp = adList.firstOrNull()
            adList.remove(temp)
            FlurryEventUtil.putDataToEvent(EventType.TYPE_IS_READY, "Native", "True_$time")
        }else{
            FlurryEventUtil.putDataToEvent(EventType.TYPE_IS_READY, "Native", "False_$time")
        }
        return temp
    }

    private fun getTestId(id: String): String {
        val adArray = arrayOf(
            "CAROUSEL_IMG_SQUARE_APP_INSTALL",
            "CAROUSEL_IMG_SQUARE_LINK",
            "IMG_16_9_APP_INSTALL",
            "IMG_16_9_LINK",
            "VID_HD_9_16_39S_APP_INSTALL",
            "VID_HD_9_16_39S_LINK",
            "VID_HD_16_9_15S_APP_INSTALL",
            "VID_HD_16_9_15S_LINK",
            "VID_HD_16_9_46S_APP_INSTALL",
            "VID_HD_16_9_46S_LINK"
        )

        return if (BuildConfig.DEBUG) {
            AdSettings.setIntegrationErrorMode(AdSettings.IntegrationErrorMode.INTEGRATION_ERROR_CRASH_DEBUG_MODE)
            AdSettings.addTestDevice("1787b2ab-0b72-4dcb-b15f-225fcfb536bf") // Mi 8
            AdSettings.addTestDevice("737dd78d-69b2-4a06-b7a0-ef0222309fe2") // Pixel 3
            val index = (adArray.indices).random()
            return if (index < adArray.size) {
//                Log.e("wsTest", adArray[index] + id)
                adArray[index] + "#$id"
            } else {
//                Log.e("wsTest", adArray[0] + id)
                adArray[0] + "#$id"
            }
        } else {
            id
        }
    }

    private var close: OnCloseListener? = null
    fun setCloseListener(listener: OnCloseListener) {
        close = listener
    }

    interface OnCloseListener {
        fun onClose()
    }

    // 单独用cpm最高的缓存
    var mNativeAdsManager: NativeAdsManager? = null
    fun loadNativeManager() { // 获取一组5个广告资源
        val placementId = "689949925164662_689985308494457"
        mNativeAdsManager = NativeAdsManager(mContext, getTestId(placementId), 5)
        mNativeAdsManager!!.loadAds()
        mNativeAdsManager!!.setListener(object : NativeAdsManager.Listener {
            override fun onAdsLoaded() {
                if (mContext == null) {
                    return
                }
                FlurryEventUtil.putDataToEvent("NativeAdsManager_Loaded", "type", "success")
            }

            override fun onAdError(p0: AdError?) {
                if (p0 != null) {
                    FlurryEventUtil.putDataToEvent(
                        EventType.TYPE_AD_DISPLAY_ERROR_MESSAGE,
                        "type",
                        p0.errorMessage.toString()
                    )
                    Log.e("---", p0.errorMessage.toString() + p0.errorCode.toString())
                }
            }

        })
    }
}